package com.hunantv.mglive.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSON;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.LiveUrlModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarLiveDataModel;
import com.hunantv.mglive.ui.live.StarLiveActivity;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by qiuda on 16/4/29.
 */
public class StartActivityDelayUtil implements HttpUtils.callBack {
    private static StartActivityDelayUtil mStartActivityDelayUtil;
    private HttpUtils mHttp;
    private Context mContext;
    private boolean mIsGetting;
    private boolean mIsStarted;
    private StarLiveDataModel mStarLiveModel;
    private Intent mIntent;
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            StartActivity(null, null);
        }
    };

    public static StartActivityDelayUtil instance(Context context) {
        if (mStartActivityDelayUtil == null) {
            mStartActivityDelayUtil = new StartActivityDelayUtil();
        }
        mStartActivityDelayUtil.resetData(context);
        return mStartActivityDelayUtil;
    }

    private StartActivityDelayUtil() {

    }

    private void resetData(Context context) {
        if (mContext != context) {
            mIsGetting = false;
            mIsStarted = false;
        }
        mHttp = new HttpUtils(context, this);
        mContext = context;

    }

    public synchronized void startAcitiy(String starId) {
        startAcitiy(starId, false);
    }

    public synchronized void startAcitiy(String starId, boolean isNewTask) {
        if (mIsGetting) {
            return;
        }
        mIsGetting = true;
        mIsStarted = false;
        mIntent = new Intent(mContext, StarLiveActivity.class);
        mIntent.putExtra(Constant.JUMP_INTENT_UID, starId);
        if (isNewTask) {
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mHandler.sendEmptyMessageDelayed(0, 1000);
        getLidByUid(starId);
    }


    private synchronized void StartActivity(StarLiveDataModel starLiveDataModel, String url) {
        if (mIsStarted || mIntent == null || mContext == null) {
            return;
        }
        mIsStarted = true;
        if (starLiveDataModel != null) {
            mIntent.putExtra(StarLiveActivity.JUMP_STAR_LIVE_MODEL, starLiveDataModel);
        }
        if (!StringUtil.isNullorEmpty(url)) {
            mIntent.putExtra(StarLiveActivity.JUMP_STAR_LIVE_PLAY_URL, url);
        }
        if (mContext != null) {
            mContext.startActivity(mIntent);
        }
        mHandler.removeMessages(0);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mContext = null;
            }
        }, 1000);
    }

    private void getLidByUid(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", MaxApplication.getApp().getUid())
                .add("auid", starId)
                .build();
        post(BuildConfig.URL_GET_LIVE_INFO_BY_UID, body);
    }

    private void loadData(String lid, String uid) {
        Map<String, String> requestBody = new FormEncodingBuilderEx().add(Constant.KEY_LID, lid).add(Constant.KEY_UID, uid).build();
        post(BuildConfig.URL_LIVE_GET_URL, requestBody);
    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {
    }


    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url)) {
            return JSON.parseObject(resultModel.getData(), StarLiveDataModel.class);
        } else if (BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            return JSON.parseArray(resultModel.getData(), LiveUrlModel.class);
        }
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url) || BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            StartActivity(null, null);
        }

    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_LIVE_INFO_BY_UID.equals(url)) {
            mStarLiveModel = (StarLiveDataModel) resultModel.getDataModel();
            loadData(mStarLiveModel.getlId(), mStarLiveModel.getUid());
        } else if (BuildConfig.URL_LIVE_GET_URL.equals(url)) {
            List<LiveUrlModel> mLiveUrls = (List<LiveUrlModel>) resultModel.getDataModel();
            String mPlayUrl = StringUtil.getPlayUrl(mLiveUrls);
            StartActivity(mStarLiveModel, mPlayUrl);

        }
    }
}
